<template>
  <div>
    <!-- 检验申请主要功能 -->
    <div>
      <el-row :gutter="20">
        <!-- 患者列表 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <div>
              <span>待查患者</span>
              <el-table
                v-loading="loading"
                :data="patientData"
                stripe
                border
                :default-sort="{ prop: 'patient_id', order: 'asc' }"
                max-height="250"
                min-height="250"
                element-loading-text="正在加载..."
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                style="width: 575px"
              >
                <el-table-column align="center" prop="patient_id" label="ID" width="100" />
                <el-table-column align="center" prop="patient_name" label="姓名" width="150" />
                <el-table-column align="center" prop="patient_age" label="年龄" width="100" />
                <el-table-column align="center" prop="patient_gender" label="性别" width="100" />
                <el-table-column align="center" fixed="right" label="操作" width="120">
                  <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" content="选择此病人，并开立检查项目" placement="right">
                      <el-button type="primary" size="mini" @click="choosePatient(scope.row)">选择</el-button>
                    </el-tooltip>

                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>

        <!-- 当前患者信息 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <el-empty v-if="!isChoose" description="暂未选择患者" />
            <div v-show="isChoose">
              <el-descriptions size="mini" title="患者基本信息" direction="vertical" :column="3" border>
                <el-descriptions-item :span="2"><template slot="label">
                  <i class="el-icon-user" />
                  姓名
                </template>{{ choosedPatient.patient_name }}</el-descriptions-item>
                <el-descriptions-item label="ID" :span="2">{{ choosedPatient.patient_id }}</el-descriptions-item>
                <el-descriptions-item :span="2"><template slot="label">
                  <i class="el-icon-mobile-phone" />
                  手机号
                </template>{{ choosedPatient.patientPhone }}</el-descriptions-item>
                <el-descriptions-item label="年龄" :span="2">{{ choosedPatient.patient_age }}</el-descriptions-item>
                <el-descriptions-item label="性别" :span="2">{{ choosedPatient.patient_gender }}</el-descriptions-item>
                <el-descriptions-item label="检验申请" :span="2">
                  <el-button size="mini" type="success" icon="el-icon-plus" @click="openAddApply" />
                </el-descriptions-item>
              </el-descriptions>

            </div>
          </el-card>
        </el-col>
      </el-row>

      <div>
        <el-divider content-position="center">患者检查项目表</el-divider>
      </div>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-card shadow="hover">
            <el-empty v-if="!isChoose" description="暂未选择患者" />
            <div v-show="isChoose" style="width: 100%">
              <el-table
                v-loading="checkApplyLoading"
                :data="applyCheckList"
                stripe
                border
                :default-sort="{ prop: 'ApplyTime', order: 'descending' }"
                element-loading-text="正在加载..."
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                style="width: 100%"
              >
                <el-table-column align="center" prop="id" label="检验ID" width="75px" />
                <el-table-column align="center" prop="patient_id" label="患者ID" width="75px" />
                <el-table-column align="center" prop="time" label="检验时间" width="100px" />
                <el-table-column align="center" prop="name" label="检验名称" width="150px" />
                <el-table-column align="center" prop="position" label="检查部位/要求" width="125px" />
                <el-table-column align="center" prop="description" label="描述备注" width="125px" />
                <el-table-column align="center" prop="price" label="项目价格" width="100px" />
                <el-table-column align="center" prop="result" label="检查结果" width="150px">
                  <template slot-scope="scope">
                    <el-popover trigger="hover" placement="top">
                      <p>结果: {{ scope.row.result }}</p>
                      <div slot="reference" class="name-wrapper">
                        <el-tag size="medium">结果</el-tag>
                      </div>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="status" label="状态" :formatter="applyState" width="113px">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.ApplyStatus != '已完成'" type="warning" size="mini">未完成</el-tag>
                    <el-tag v-if="scope.row.ApplyStatus === '已完成'" type="success" size="mini">已完成</el-tag>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作" width="150px">
                  <template slot-scope="scope">
                    <el-button-group>
                      <div>
                        <el-button
                          v-if="scope.row.ApplyStatus != '已完成'"
                          style="color: #0796b8"
                          type="text"
                          size="mini"
                          :disabled="scope.row.ApplyStatus === '已完成'"
                          @click="openEditApply(scope.row)"
                        >编辑</el-button>
                        <el-button
                          v-else
                          type="text"
                          size="mini"
                          :disabled="scope.row.ApplyStatus === '已完成'"
                          @click="openEditApply(scope.row)"
                        >编辑</el-button>
                      </div>
                    </el-button-group>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!-- 申请弹窗 -->
    <div>
      <el-dialog title="修改项目" :visible.sync="editDialogVisible" width="80%" @close="editDialogVisible = false; resetApply('addApplyForm')">
        <el-form ref="addApplyForm" :model="addApplyForm" :rules="addApplyFormRules" width="80%">
          <el-descriptions class="margin-top" :column="3" size="small" border>
            <el-descriptions-item label="检验名称">
              <template>
                <el-form-item prop="apply_name">
                  <el-cascader
                    v-model="addApplyForm.apply_name"
                    placeholder="输入检验名称"
                    :options="options"
                    filterable
                    clearable
                    :props="{ expandTrigger: 'hover' }"
                    @change="handleChange111"
                  />
                </el-form-item>
              </template>
            </el-descriptions-item>
            <el-descriptions-item label="检查部位/要求">
              <template>
                <el-form-item prop="apply_position">
                  <el-select
                    v-model="addApplyForm.apply_position"
                    multiple
                    filterable
                    placeholder="输入检查部位/要求"
                    @change="handleChange222"
                  >
                    <el-option
                      v-for="item in positionOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-descriptions-item>
            <el-descriptions-item label="描述备注">
              <template>
                <el-form-item prop="apply_description">
                  <el-input v-model="addApplyForm.apply_description" type="textarea" placeholder="请输入描述备注" />
                </el-form-item>
              </template>
            </el-descriptions-item>
            <el-descriptions-item label="当前检查总价">
              {{ totalPrice }}元
            </el-descriptions-item>
          </el-descriptions>
        </el-form>
        <div slot="footer">
          <el-button-group>
            <el-button type="info" icon="el-icon-refresh" @click="resetApply('addApplyForm')">重 置</el-button>
            <el-button type="primary" icon="el-icon-close" @click="editDialogVisible = false; resetApply('addApplyForm')">取 消</el-button>
            <el-button type="success" icon="el-icon-plus" @click="editApply('addApplyForm')">添 加</el-button>
          </el-button-group>

        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { DocterCreateNewCheck, DocterGetPaientCheckList, DocterUpdateCheck } from '@/api/checkApply'
// import { DocterCreateNewCheck, DocterGetPaientCheckList } from '@/api/checkApply'
import { DocterGetCurrentPaient } from '@/api/medicalEdit'
export default {
  name: 'CheckApply',
  data() {
    return {
      presentUser: {},
      totalPrice: 888,
      addDialogVisible: false,
      editDialogVisible: false,
      loading: false,
      checkApplyLoading: false,
      isChoose: false,
      // 患者列表
      patientData: [{
        patient_id: 1,
        patient_name: '小明',
        patient_age: '22',
        patient_gender: '男',
        patientPhone: '13340287626',
        patientAddress: '重庆市渝北区',
        patientstatus: '已诊'
      },
      {
        patient_id: 2,
        patient_name: '小红',
        patient_age: '25',
        patient_gender: '女',
        patientPhone: '13840287626',
        patientAddress: '重庆市南岸区',
        patientstatus: '待诊'
      },
      {
        patient_id: 3,
        patient_name: '小刚',
        patient_age: '30',
        patient_gender: '男',
        patientPhone: '13940287626',
        patientAddress: '重庆市沙坪坝区',
        patientstatus: '待诊'
      },
      {
        patient_id: 6,
        patient_name: '小刚',
        patient_age: '30',
        patient_gender: '男',
        patientPhone: '13940287626',
        patientAddress: '重庆市沙坪坝区',
        patientstatus: '待诊'
      },
      {
        patient_id: 5,
        patient_name: '小刚',
        patient_age: '30',
        patient_gender: '男',
        patientPhone: '13940287626',
        patientAddress: '重庆市沙坪坝区',
        patientstatus: '待诊'
      },
      {
        patient_id: 4,
        patient_name: '小刚',
        patient_age: '30',
        patient_gender: '男',
        patientPhone: '13940287626',
        patientAddress: '重庆市沙坪坝区',
        patientstatus: '待诊'
      }],
      // 当前患者
      choosedPatient: {
        appointment_id: '',
        patient_id: '',
        patient_name: '',
        patientPhone: '',
        patient_gender: '',
        patient_age: ''
      },
      // 检验列表
      applyCheckList: [
        // {
        //   ApplyId: 1,
        //   ApplyPrice: 1200,
        //   apply_name: '血常规',
        //   apply_position: '全血',
        //   apply_description: '是血常规检查',
        //   ApplyStatus: 1,
        //   ApplyTime: '2020-05-05 12:00:00',
        //   ApplyResult: '正常',
        //   patient_id: 3,
        //   doctorId: 3
        // },
        // {
        //   ApplyId: 2,
        //   ApplyPrice: 1200,
        //   apply_name: '白细胞计数(WBC)',
        //   apply_position: '背部',
        //   apply_description: '需要两张',
        //   ApplyStatus: 2,
        //   ApplyTime: '2020-05-05 12:00:00',
        //   ApplyResult: '异常',
        //   patient_id: 3,
        //   doctorId: 3
        // },
        // {
        //   ApplyId: 3,
        //   ApplyPrice: 1200,
        //   apply_name: '皮试',
        //   apply_position: '背部wefwef',
        //   apply_description: '需要两张efwefwef',
        //   ApplyStatus: 2,
        //   ApplyTime: '2020-06-05 12:00:00',
        //   ApplyResult: '手动阀手动阀',
        //   patient_id: 3,
        //   doctorId: 3
        // },
        // {
        //   ApplyId: 5,
        //   ApplyPrice: 1200,
        //   apply_name: '尿检',
        //   apply_position: '背部',
        //   apply_description: '需要两张',
        //   ApplyStatus: 2,
        //   ApplyTime: '2019-05-05 12:00:00',
        //   ApplyResult: '大师傅撒旦发生',
        //   patient_id: 3,
        //   doctorId: 3
        // },
        // {
        //   ApplyId: 4,
        //   ApplyPrice: 1200,
        //   apply_name: '的方式',
        //   apply_position: '的萨芬',
        //   apply_description: '手动阀',
        //   ApplyStatus: 1,
        //   ApplyTime: '2022-05-05 12:00:00',
        //   ApplyResult: '的撒法大师傅',
        //   patient_id: 3,
        //   doctorId: 3
        // }
      ],
      // 当前检验
      curApply: {
        apply_id: '',
        apply_name: '',
        apply_position: '',
        apply_description: '',
        apply_price: 8,
        apply_result: ''
      },
      // 添加检验
      addApplyForm: {
        apply_id: '',
        apply_name: '',
        apply_position: '',
        apply_description: '',
        apply_price: 8,
        apply_result: ''
      },
      addApplyFormRules: {
        apply_name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        apply_position: [{ required: true, message: '请输入检查部位', trigger: 'blur' }]
      },
      options: [
        {
          value: '化验类',
          label: '化验类',
          children: [
            {
              value: '血液检查',
              label: '血液检查',
              children: [
                {
                  value: '血常规项目',
                  label: '血常规项目'
                },
                {
                  value: '生化检查项目',
                  label: '生化检查项目'
                }
              ]
            },
            {
              value: '体液检查',
              label: '体液检查',
              children: [
                {
                  value: '尿液检查',
                  label: '尿液检查'
                },
                {
                  value: '粪便检查',
                  label: '粪便检查'
                }
              ]
            }
          ]
        },
        {
          value: '放射科类',
          label: '放射科类',
          children: [
            {
              value: 'X线检查',
              label: 'X线检查'
            },
            {
              value: 'CT检查',
              label: 'CT检查'
            },
            {
              value: '造影检查',
              label: '造影检查'

            }
          ]
        },
        {
          value: '超声检查类',
          label: '超声检查类',
          children: [
            {
              value: '腹部超声',
              label: '腹部超声'

            },
            {
              value: '心血管超声',
              label: '心血管超声'

            }
          ]
        }
      ],
      positionOptions: [
      ],
      positionOptions1_1_1: [
        {
          value: '白细胞计数(WBC)',
          label: '白细胞计数(WBC)'
        }, {
          value: '红细胞计数(RBC)',
          label: '红细胞计数(RBC)'
        }, {
          value: '血红蛋白(Hb)',
          label: '血红蛋白(Hb)'
        },
        {
          value: '红细胞分布宽度(RDW)',
          label: '红细胞分布宽度(RDW)'
        }
      ],
      positionOptions1_1_2: [
        {
          value: '肝功能检查',
          label: '肝功能检查'
        },
        {
          value: '肾功能检查',
          label: '肾功能检查'
        },
        {
          value: '血脂检查',
          label: '血脂检查'
        },
        {
          value: '血糖检查',
          label: '血糖检查'
        }
      ],
      positionOptions1_2_1: [
        {
          value: '尿常规项目',
          label: '尿常规项目'
        },
        {
          value: '尿沉渣检查',
          label: '尿沉渣检查'
        },
        {
          value: '24 小时尿蛋白定量',
          label: '24 小时尿蛋白定量'
        }
      ],
      positionOptions1_2_2: [
        {
          value: '粪便常规项目',
          label: '粪便常规项目'
        },
        {
          value: '粪便潜血试验',
          label: '粪便潜血试验'
        }
      ],
      positionOptions2_1: [
        {
          value: '胸部X线',
          label: '胸部X线'
        }, {
          value: '骨骼X线',
          label: '骨骼X线'
        }
      ],
      positionOptions2_2: [
        {
          value: '头颅 CT',
          label: '头颅 CT'
        },
        {
          value: '胸部 CT',
          label: '胸部 CT'
        },
        {
          value: '腹部 CT',
          label: '腹部 CT'
        },
        {
          value: '脊柱 CT',
          label: '脊柱 CT'
        }
      ],
      positionOptions2_3: [
        {
          value: '消化道造影',
          label: '消化道造影'
        },
        {
          value: '血管造影',
          label: '血管造影'
        },
        {
          value: '尿路造影',
          label: '尿路造影'
        }
      ],
      positionOptions3_1: [
        {
          value: '肝脏超声',
          label: '肝脏超声'
        }, {
          value: '胆囊超声',
          label: '胆囊超声'
        }
      ],
      positionOptions3_2: [
        {
          value: '心脏超声（超声心动图）',
          label: '心脏超声（超声心动图）'
        },
        {
          value: '血管超声',
          label: '血管超声'
        }
      ],
      prices: {
        '白细胞计数(WBC)': 50,
        '红细胞计数(RBC)': 40,
        '血红蛋白(Hb)': 35,
        '红细胞分布宽度(RDW)': 45,
        肝功能检查: 80,
        肾功能检查: 75,
        血脂检查: 60,
        血糖检查: 55,
        尿常规项目: 30,
        尿沉渣检查: 25,
        '24 小时尿蛋白定量': 65,
        粪便常规项目: 20,
        粪便潜血试验: 28,
        胸部X线: 100,
        骨骼X线: 120,
        '头颅 CT': 200,
        '胸部 CT': 250,
        '腹部 CT': 300,
        '脊柱 CT': 350,
        消化道造影: 400,
        血管造影: 450,
        尿路造影: 500,
        肝脏超声: 80,
        胆囊超声: 90,
        '心脏超声（超声心动图）': 150,
        血管超声: 120
      }
    }
  },

  mounted() {
    this.presentUser = JSON.parse(localStorage.getItem('User'))
    console.log('初始化医生：', this.presentUser)
    // TODO:用doctorid去获取患者列表
    this.initPatient()
  },

  methods: {

    async openAddApply() { // 新建检验
      const data = {
        apply_patient_id: this.choosedPatient.patient_id,
        apply_doctor_id: this.presentUser.doctor_id,
        appointment_id: this.choosedPatient.appointment_id
      }
      console.log('新建检验申请病人id：', data)
      // axio
      await DocterCreateNewCheck(data)
      this.initApply(this.choosedPatient.patient_id)// 初始化已选择患者的检查申请表信息
    },
    openEditApply(row) { // 打开编辑检验的弹窗
      this.editDialogVisible = true
      this.addApplyForm.apply_id = row.id
      this.addApplyForm.apply_name = []
      this.addApplyForm.apply_price = row.price || 0
      this.addApplyForm.apply_position = []
      this.addApplyForm.apply_description = row.description || ''
      this.totalPrice = row.price || 0

      // 确保 positionOptions 在打开弹窗时被正确设置
      this.handleChange111(this.addApplyForm.apply_name)

      console.log('编辑申请:', this.addApplyForm)
    },
    deleteApply(row) { // 删除检验

    },
    choosePatient(row) {
      console.log(row)
      this.$nextTick(() => {
        this.isChoose = true
        this.choosedPatient.patient_name = row.patient_name
        this.choosedPatient.patientPhone = row.patientPhone
        this.choosedPatient.patient_id = row.patient_id
        this.choosedPatient.patient_gender = row.patient_gender
        this.choosedPatient.patient_age = row.patient_age
        this.choosedPatient.appointment_id = row.appointment_id
      })

      // 准备获取当前患者的检查列表
      this.initApply(row.patient_id)// 初始化已选择患者的检查申请表信息
    },
    async initPatient() {
      this.loading = true
      const parsedPatient = JSON.parse(localStorage.getItem('patient'))
      console.log('获取当前患者的检查列表：', parsedPatient)
      const data = { appointment_id: parsedPatient.appointment_id }
      console.log('获取当前患者的检查列表：', data)
      const res = await DocterGetCurrentPaient(data)
      this.patientData = res
      this.loading = false
    },
    async initApply(number) {
      // 初始化当前病人的检查申请列表
      const data = {
        patient_id: number
      }
      console.log('检查申请列表：', data)
      const res = await DocterGetPaientCheckList(data)
      this.applyCheckList = res.applys
      // console.log('检查申请列表：', this.applyCheckList)
    },
    applyState(row, column) {
      switch (row[column.property]) {
        case 1:
          return '未缴费'
        case 2:
          return '已完成'
        case 3:
          return '已缴费'
        case 4:
          return '已退费'
      }
    },
    handleChange111(value) {
      this.positionOptions = []
      console.log(value)

      // 检查 value 是否为 undefined 或 null
      if (!value) {
        console.warn('Value is undefined or null:', value)
        return
      }

      // 将 value 转换为字符串
      const valueStr = Array.isArray(value) ? value.join(',') : value.toString()

      // 根据不同的 value 设置 positionOptions
      if (valueStr === '化验类,血液检查,血常规项目') {
        this.positionOptions = this.positionOptions1_1_1
      } else if (valueStr === '化验类,血液检查,生化检查项目') {
        this.positionOptions = this.positionOptions1_1_2
      } else if (valueStr === '化验类,体液检查,尿液检查') {
        this.positionOptions = this.positionOptions1_2_1
      } else if (valueStr === '化验类,体液检查,粪便检查') {
        this.positionOptions = this.positionOptions1_2_2
      } else if (valueStr === '放射科类,X线检查') {
        this.positionOptions = this.positionOptions2_1
      } else if (valueStr === '放射科类,CT检查') {
        this.positionOptions = this.positionOptions2_2
      } else if (valueStr === '放射科类,造影检查') {
        this.positionOptions = this.positionOptions2_3
      } else if (valueStr === '超声检查类,腹部超声') {
        this.positionOptions = this.positionOptions3_1
      } else if (valueStr === '超声检查类,心血管超声') {
        this.positionOptions = this.positionOptions3_2
      }
    },

    handleChange222(value2) {
      console.log('Selected Positions:', value2)

      // 清零总价
      this.totalPrice = 0

      value2.forEach(position => {
        if (this.prices[position]) {
          this.totalPrice += this.prices[position]
        }
      })

      console.log('Total Price:', this.totalPrice)
    },

    resetApply(formName) {
      console.log('重置')
      this.addApplyForm = { // 注意不能直接为空
        apply_id: '',
        apply_name: [],
        apply_position: [],
        apply_description: '',
        apply_price: 8
      }
      this.positionOptions = []
      this.totalPrice = 0
      this.$refs[formName].resetFields()
    },
    async editApply(formName) { // 编辑
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          const data1 = {
            apply_id: this.addApplyForm.apply_id,
            apply_name: this.addApplyForm.apply_name.toString(),
            apply_position: this.addApplyForm.apply_position.toString(),
            apply_description: this.addApplyForm.apply_description,
            apply_price: this.totalPrice,
            apply_result: '还没有检查'
          }
          console.log('编辑检查申请：', data1)
          await DocterUpdateCheck(data1)
          this.editDialogVisible = false
          this.$refs[formName].resetFields()
          this.initApply(this.choosedPatient.patient_id)
        }
      })
    }
  }
}
</script>

<style></style>
